package pers.kw.protocol;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;

import java.util.Map;

/**
 * 请求成功响应封装
 *
 * @param <T>
 */
public class R<T> {
    private final Integer status;
    private final String msg;
    private final Map<String, String> headers;
    private T body;

    public R(Integer status, String msg, Map<String, String> headers) {
        this.status = status == null ? HttpStatus.INTERNAL_SERVER_ERROR.value() : status;
        this.msg = msg;
        this.headers = headers;
    }

    public R(Integer status, String msg, Map<String, String> headers, T body) {
        this.status = status == null ? HttpStatus.INTERNAL_SERVER_ERROR.value() : status;
        this.msg = msg;
        this.headers = headers;
        this.body = body;
    }


    public R(Integer status, String msg) {
        this(status, msg, null);
    }

    public R(Integer status) {
        this(status, (String) null, null);
    }

    public static R ok() {
        return new R(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), null);
    }

    public static <T> R<T> ok(T body) {
        return new R(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), null, body);
    }

    public static R fail(Integer status, String msg) {
        return new R(status, msg, null);
    }

    public boolean isOk() {
        return HttpStatus.OK.value() == this.status;
    }

    public String toJsonString() {
        return JSONObject.toJSONString(this);
    }

    public Integer getStatus() {
        return this.status;
    }

    public String getMsg() {
        return this.msg;
    }

    public Map<String, String> getHeaders() {
        return this.headers;
    }

    public T getBody() {
        return body;
    }
}

